/*--------------------------------------------------------------------------
 *  Copyright 2011 Taro L. Saito
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *--------------------------------------------------------------------------*/
//--------------------------------------
// XerialJ
//
// Master.java
// Since: 2011/02/03 17:25:21
//
// $URL$
// $Author$
//--------------------------------------
package org.xerial.silk.weaver.cui;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelState;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;
import org.xerial.util.log.Logger;
import org.xerial.util.opt.Option;

/**
 * Launch a master server
 * 
 * @author leo
 * 
 */
public class Master extends WeaverCommand
{
    private static Logger _logger = Logger.getLogger(Master.class);

    // program options
    @Option(symbol = "p", description = "port number. default = 8080")
    int                   port    = 8080;

    @Override
    public String name() {
        return "master";
    }

    @Override
    public String getOneLineDescription() {
        return "launch a master server";
    }

    @Override
    public Object getOptionHolder() {
        return this;
    }

    @Override
    public void execute(String[] args) throws Exception {

        ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new ObjectEncoder(), new ObjectDecoder(), new ObjectServerHandler());
            }
        });

        bootstrap.setOption("reuseAddress", true);
        bootstrap.setOption("tcpNoDelay", true);

        Channel bind = bootstrap.bind(new InetSocketAddress(port));
        bind.getCloseFuture().awaitUninterruptibly();
    }

    public class ObjectServerHandler extends SimpleChannelUpstreamHandler
    {
        private final AtomicLong transferredMessages = new AtomicLong();

        @Override
        public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
            if (e instanceof ChannelStateEvent && ((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) {
                _logger.info(e.toString());
            }
            super.handleUpstream(ctx, e);
        }

        @Override
        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
            transferredMessages.incrementAndGet();
            Object m = e.getMessage();
            _logger.info("recieved a message: " + m);
            e.getChannel().write("Nice to meet you!");
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
            _logger.warn(e.getCause());
            e.getChannel().close();
        }
    }
}
